package cn.com.nxt.txb;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import cn.com.nxt.txb.httpdelegate.UserDelegate;
import cn.com.nxt.txb.model.User;
import cn.com.nxt.txb.util.AppConstant;
import cn.com.nxt.txb.util.AppUtil;
import cn.com.nxt.txb.util.AuthPreferences;
import cn.com.nxt.txb.util.CountDownTimerUtils;
import cn.com.nxt.txb.util.UserPreferences;
import cn.com.nxt.txb.widget.ClearEditText;

import static android.Manifest.permission.READ_CONTACTS;

/**
 * A login screen that offers login via email/password.
 */
@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity {
    public static final byte RESULT_REGISTER = 0x000;// 注册成功时返回
    @ViewInject(R.id.et_phone)
    private ClearEditText mPhoneEt;
    @ViewInject(R.id.et_password)
    private ClearEditText mPwdEt;
    private String mPhone, mPwd;
    private Button mLoginBtn;
    private Button mLoginBtn2;
    private byte loginFlag = 0x002;
    private UserDelegate delegate;
    @ViewInject(R.id.iv_eye)
    private ImageView mIvEye;

    private boolean mIsPasswordShow = false;
    private static final String KICK_OUT = "KICK_OUT";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);//注解绑定
        mLoginBtn = (Button) findViewById(R.id.btn_1);
        mLoginBtn2 = (Button) findViewById(R.id.btn_2);
        mLoginBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // attemptLogin();
                doLogin("000005", "81f6602823338791c72a087ac679c035");
            }
        });
        mLoginBtn2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // attemptLogin();
                doLogin("000006", "3cbc5af2146fb024fb7d5037abad7e4c");
            }
        });
        delegate = new UserDelegate(LoginActivity.this);

        //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }

    private void saveLoginInfo(final String account, final String token) {
        AuthPreferences.saveUserAccount(account);
        AuthPreferences.saveUserToken(token);
        //AuthPreferences.saveUserName(name);
    }

    @Event({R.id.tv_register, R.id.tv_forget_password, R.id.tv_login, R.id.iv_eye})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.tv_register:
                Intent intent = new Intent(LoginActivity.this,
                        RegisterActivity.class);
                startActivityForResult(intent, RESULT_REGISTER);
                break;
            case R.id.tv_forget_password:
                Intent intent2 = new Intent(LoginActivity.this,
                        RetrievePasswordActivity.class);
                startActivityForResult(intent2, RESULT_REGISTER);
                break;
            case R.id.tv_login:
                login();
                break;
            case R.id.iv_eye:
                passwordShowOrHidden();
                break;
        }
    }

    private void passwordShowOrHidden() {
        if (mIsPasswordShow) {
            //选择状态 显示明文--设置为可见的密码
            mPwdEt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            mIvEye.setImageResource(R.drawable.eye_close);
        } else {
            //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
            mPwdEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            mIvEye.setImageResource(R.drawable.eye);
        }
        mIsPasswordShow=!mIsPasswordShow;
    }

    private void login() {
        mPhone = mPhoneEt.getText().toString().trim();
        if (TextUtils.isEmpty(mPhone)) {
            showToast("手机号不能为空！");
            return;
        }
        mPwd = mPwdEt.getText().toString().trim();
        if (TextUtils.isEmpty(mPwd)) {
            showToast("密码不能为空！");
            return;
        }
        User user = new User();
        user.setPhone(mPhone);
        user.setPassword(mPwd);
        Gson gson = new Gson();
        showDialog("正在登录");
        AppUtil.mUser=user;
        Log.v("--login--",gson.toJson(user));
        delegate.login(gson.toJson(user), loginFlag);
    }

    @Override
    public void success(String result, byte flag) {
        super.success(result, flag);
        disDialog();
        Gson gson = new Gson();
        User user = gson.fromJson(result, User.class);
        user.setPhone(mPhone);
       // showToast("登录成功："+user.getRommid());
         AppUtil.mUser=user;
         AppUtil.saveUser(LoginActivity.this,user);
        // showToast("成功："+user.getToken());
//        Intent intent = new Intent();
//        Bundle bundle = new Bundle();
//        bundle.putSerializable("user",user);
//        intent.putExtras(bundle);
//        setResult(LoginActivity.RESULT_REGISTER, intent);
//        startActivity(new Intent(LoginActivity.this, MainActivity.class));
//        finish();
        //showToast(user.getToken()+"成功："+user.getPhone());
        doLogin(user.getPhone(), user.getToken());
    }

    @Override
    public void failure(String result, byte flag, ResponseStatus status) {
        super.failure(result, flag, status);
        disDialog();
        showToast(result);
    }

    @Override
    public void finished(int flag) {
        disDialog();
    }

    @Override
    public void cancelled(int flag) {
        disDialog();
    }

    public void doLogin(final String account, final String token) {
        LoginInfo info = new LoginInfo(account, token); // config...
        RequestCallback<LoginInfo> callback =
                new RequestCallback<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo loginInfo) {
                       // startActivity(new Intent(LoginActivity.this, MQTTService.class));

                      //  bindService(new Intent(LoginActivity.this, MQTTService.class), SampleApplicationLike.conn, BIND_AUTO_CREATE);
                        // Log.i("--LOGIN--", "login success");
                        //showToast("--LOGIN--"+account);
                        //SampleApplicationLike.mqttBinder.subscribe("/meetting/invlite/:"+AppUtil.mUser.getPhone());
                        DemoCache.setAccount(account);
                        saveLoginInfo(account, token);
                        // 初始化消息提醒
                        NIMClient.toggleNotification(UserPreferences.getNotificationToggle());
                        // 初始化免打扰
                        NIMClient.updateStatusBarNotificationConfig(UserPreferences.getStatusConfig());
                        // 进入主界面
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    }

                    @Override
                    public void onFailed(int code) {
                        if (code == 302 || code == 404) {
                            Toast.makeText(LoginActivity.this, R.string.login_failed, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(LoginActivity.this, "登录失败: " + code, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onException(Throwable throwable) {

                    }
                    // 可以在此保存LoginInfo到本地，下次启动APP做自动登录用
                };
        NIMClient.getService(AuthService.class).login(info)
                .setCallback(callback);
    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent data) {
        super.onActivityResult(arg0, arg1, data);
        if (data == null)
            return;
        User user = (User) data.getSerializableExtra("user");
        mPhoneEt.setText(user.getPhone());
        //AppUtil.mUser=user;
        // AppUtil.saveUser(RegisterActivity.this,user);
    }

    public static void start(Context context, boolean kickOut) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(KICK_OUT, kickOut);
        context.startActivity(intent);
    }
}

